using System;
using System.Runtime.InteropServices;

using Pegasus.Windows.API;
using Pegasus.Windows.API.Enumerations;

namespace Pegasus.Windows.Shell
{
	/// <summary>
	/// This is a specal wrapper class for the shell ITEMIDLIST (or Pointer Item Id List, PIDL).
	/// </summary>
	public class Pidl : IDisposable
	{
		// Local Instance Values
		private IntPtr m_ipPidl = IntPtr.Zero;

		/// <summary>
		/// Initializes a new instance of the <see cref="Pidl"/> class.  Pidl 
		/// represents the Desktop item or root of the namesame.
		/// </summary>
		public Pidl()
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Pidl"/> class.
		/// </summary>
		/// <param name="ipPidl">The ip pidl.</param>
		public Pidl( IntPtr ipPidl )
		{
			m_ipPidl = ipPidl;
		}

		/// <summary>
		/// Implicit operators that return the IntPtr for a PIDL object.
		/// </summary>
		/// <param name="pidl">The pidl object.</param>
		/// <returns>The point to the system ITEMIDLIST.</returns>
		public static implicit operator IntPtr( Pidl pidl )
		{
			return pidl.m_ipPidl;
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			if( m_ipPidl != IntPtr.Zero )
			{
				Marshal.FreeCoTaskMem( m_ipPidl );
				m_ipPidl = IntPtr.Zero;
			}
		}

		/// <summary>
		/// Gets the PIDL for a special folder object.
		/// </summary>
		/// <param name="folder">The folder.</param>
		/// <returns></returns>
		public static Pidl GetSpecialFolder( CSIDL folder )
		{
			IntPtr ipPidl = IntPtr.Zero;
			Shell32.SHGetSpecialFolderLocation( IntPtr.Zero, folder, out ipPidl );

			return new Pidl( ipPidl );
		}
	}
}
